﻿using UnityEngine;
using System.Collections;

public class CloudColliderScript : MonoBehaviour {

	GameObject instantiantedClouds;
	GameObject [] clouds;
	SpriteRenderer [] spriteRenderers;
	// Use this for initialization
	void Start () {
		//Debug.Log ("GOT HERE");
		this.instantiantedClouds = (GameObject)GameObject.Find ("InstantiatedClouds");
		clouds = new GameObject[this.instantiantedClouds.transform.childCount];
		spriteRenderers = new SpriteRenderer[this.instantiantedClouds.transform.childCount];
		for (int z=0; z<clouds.Length; z++) {
			clouds[z] = this.instantiantedClouds.transform.GetChild(z).gameObject;
			spriteRenderers[z] = (SpriteRenderer)clouds[z].GetComponent(typeof(SpriteRenderer));
		}
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnTriggerEnter2D(Collider2D other) {
		//Debug.Log (other.transform.name);
		float newX = other.transform.position.x;
		// Find Max with same name and append
		for (int z=0; z<clouds.Length; z++) {
			if (clouds[z].name == other.gameObject.name) {
				float newPosX = clouds[z].transform.position.x + spriteRenderers[z].bounds.size.x;
				if (newPosX > newX) {
					//Debug.Log("CHANGE NEWX");
					//if (z == 0) {
					//	Debug.Log(newX);
					//}
					//Debug.Log(z + " - " + clouds[z].transform.position.x + " - " + spriteRenderers[z].bounds.size.x);
					newX = newPosX;
				}
			}
		}
		other.transform.position = new Vector3(newX, other.transform.position.y, other.transform.position.z);
	}
}
